package adrian.sunlight.jsp.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.HashMap;
import java.util.Vector;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import adrian.sunlight.jsp.core.Setup;
import adrian.sunlight.jsp.database.DBConnectionLostException;
import adrian.sunlight.jsp.database.dbTables;
import adrian.sunlight.jsp.util.Validate;

import com.dyuproject.oauth.Token;
import com.dyuproject.util.http.HttpConnector.Response;

/**
 * Servlet implementation class GoogleContactsImport
 */
public class GoogleContactsImport extends GoogleOAuthServlet {
	private static final long serialVersionUID = 1L;
	
	private Vector<String> Emails;
	
    /**
     * Default constructor. 
     */
    public GoogleContactsImport() {
    		Emails = new Vector<String>();
    }
    
    @Override
    protected void queryGoogleService(Token token, HttpServletRequest request, HttpServletResponse response) throws IOException{
    	
    	Response contactsRawXML = serviceGET(GOOGLE_SERVICE_URL, _consumer.getConsumerContext(), _googleEndpoint, token);
    	
    	response.setContentType("text/html");

        BufferedReader br = new BufferedReader(new InputStreamReader(contactsRawXML.getInputStream(), "UTF-8"));
        
        String line=null;
        
        while((line=br.readLine())!=null){
        	if(line.length() > 0){
        		parseMails(line);
        	}
        } 
    	
        //----realizeaza conexiunea la baza de date------------//
    	String  currentPath = request.getScheme() + "://" + request.getServerName() 
    		+ ":" + request.getLocalPort() + "" + request.getContextPath();
    	 
        Setup mySetup = new Setup();
        mySetup.init(new URL(currentPath + "/config/config.xml"));
         
        //--------parseaza contactele---------// 
        HashMap<String, String> values  = new HashMap<String, String>();
         
        HttpSession session = request.getSession();
         
        values.put("id_user", session.getAttribute("id_user").toString());

        if(Emails.size() > 0){
        	for(int i=0; i<Emails.size(); i++){
        		 
        		values.remove("contact");
        		values.put("contact", Emails.get(i).toString());
        		 
        		try {
        			mySetup.Database.insert(dbTables.CONTACTS, values);
        		} catch (DBConnectionLostException e) {
					Setup.Error = e.toString();
				}
        	 }
        }
        
        ServletOutputStream os = response.getOutputStream();
        os.println("<h3>Contactele au fost parsate!</h3>");
    }
    
    
    protected void parseMails(String text){
    	
    	Validate valid = new Validate();
    	
    	int x = 0;
    	int y = 0;
    	int index;
    	
    	if(text.length() > 0){
    		for(int i=0; i<text.length(); i++){
    			
    			String s = String.valueOf(text.charAt(i));
    			
    			if(s.equals(">")){//se temina un tag
    				x = i+1;
    			}
    			
    			if((x > 0) && s.equals("<")){//incepe un tag
    				y = i;  
    			}
    			
    			if( (x>0) && (y>x) ){//avem un cuvant
    				String sub = text.substring(x, y);
    				
    				if(valid.is_valid_email(sub)){
    					index = Emails.indexOf(sub);
    					
    					if(index < 0){
    						Emails.add(sub);
    					}
    				}
    			}
    		}
    	}
    }

}
